<!--数据库配置 add by gaojingyu-->
<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters" @submit.native.prevent>
                <el-form-item>
                    <el-input v-model="filters.name"   prefix-icon="el-icon-search" placeholder="数据库名称" @keyup.enter.native="getDatebaseList"></el-input>
                </el-form-item>
                    <el-button type="primary" @click="getDatebaseList">查询</el-button>
                </el-form-item>
            </el-form>
        </el-col>
        <!--列表-->
        <el-table :data="dbList" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" min-width="5%">
            </el-table-column>
            <el-table-column type="index" align="center" :index='indexMethod' label="序号" />
            <el-table-column prop="id" label="id" min-width="15%" :show-overflow-tooltip="true">
            </el-table-column>


            <el-table-column prop="name" label="name" min-width="15%" :show-overflow-tooltip="true">
            </el-table-column>
            
            <el-table-column prop="port" label=" port" min-width="15%" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column prop="user" label=" user" min-width="15%" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="操作" min-width="25%">
                <template slot-scope="scope">
                    <el-button  plain  type="success"  size="small" @click="handleBackup(scope.$index, scope.row)">备份</el-button>
                </template>
            </el-table-column>
        </el-table>
           <!--工具条-->
        <el-col :span="24" class="toolbar">
        <el-button  plain type="danger" size="small"  @click="back" >返回</el-button>
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="20" :page-count="total" style="float:right;">
            </el-pagination>
        </el-col>
        <!--备份弹窗界面-->
        <el-dialog title="数据库备份配置" :visible.sync="backupFormVisible" :close-on-click-modal="false" style="width: 100%">
            <el-form :model="addForm" label-width="100px" :rules="addFormRules" ref="addForm">
               <h3> 数据库名称:{{databaseName}}</h3>
               <br/>
               <a class="color-red">注:数据表至少选择一个</a><br/><br/><br/>
                <el-form-item label="请选择表:" prop="table" label-width="100px">
                    <el-select @change="handleSelect($event)"  style="width:300px" v-model="selectVal" placeholder="请选择" multiple collapse-tags>
                        <el-option
                        v-for="item in array"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                    <div>{{this.selectVal}}</div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="backupFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="backupDB" :loading="addLoading">备份</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    //import NProgress from 'nprogress'

   import { getDatebase,getApiList,editStatus_case,getApiListByProjectID,getProjectList,test
        //addEnvironment,delEnvironment,updateEnvironment
        //, delProject, disableProject, enableProject,
    ,addDatabase,getTablebyDbID

    } from '../../../../api/api';

    // import ElRow from "element-ui/packages/row/src/row";
    export default {
        // components: {ElRow},
        data() {
            return {
                databaseName:'',
                databaseId:'',


                array: [],
                selectVal: [],
                oldSelectVal: [],

                filters: {
                    name: ''
                },
                inputText:'',
                detailFormVisible:false,
                limitNum:1,
                project: [],
                dbList:[],
                total: 0,
                totalCount:0,
                page: 1,
                listLoading: false,
                uploadurl:test + '/api/api/CaseExcleImport',
                sels: [],//列表选中列
                fileList: [],
                uploadform: false,
                // getAPIFirstID=[], //getProjectFirstID:'',
                // getAPIFirstID:'',//获取接口
                editFormVisible: false,//编辑界面是否显示
                editLoading: false,
                form: {
                    getProjectFirstID:'',
                    getAPIFirstIDS:''},
                //options: [{ label: "Web", value: "Web"}, { label: "App", value: "App"}],

                editFormRules: {
                    env_name: [
                        { required: true, message: '请输入环境名称', trigger: 'blur' },
                        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
                    ],

                    address: [
                        { required: true, message: '请输入地址', trigger: 'blur' },
                        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
                    ],
                    content: [
                        { required: true, message: '请输入描述', trigger: 'blur' },
                        { max: 255, message: '不能超过125个字符', trigger: 'blur' }
                    ]
                },
                //编辑界面数据
                editForm: {
                    name: '',
                    version: '',
                    type: '',
                    description: ''
                },
                templateDownload:false,
                addFormVisible: false,//新增界面是否显示
                backupFormVisible: false,//新增界面是否显示
                addLoading: false,
                addFormRules: {
                    env_name: [
                        { required: true, message: '请输入环境名称', trigger: 'blur' },
                        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
                    ],

                    address: [
                        { required: true, message: '请输入地址', trigger: 'blur' },
                        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
                    ],
                    content: [
                        { required: true, message: '请输入描述', trigger: 'blur' },
                        { max: 255, message: '不能超过125个字符', trigger: 'blur' }
                    ]
                },
                //新增界面数据
                addForm: {
                    name: '',
                    version: '',
                    type: '',
                    description: ''
                }

            }
        },
        methods: {
            // 获取项目列表 getLyzdEnvironments getLyzdEnvironments getLyzdCaseList  interface_id
            getDatebaseList() {
                this.listLoading = true;
                let self = this;
                let params = {
                    page: self.page,
                    // interface_id: self.filters.interface_id,
                    name:self.filters.name
                };
                let headers = {Authorization: 'Token '+JSON.parse(sessionStorage.getItem('token'))};
                getDatebase(headers, params).then((res) => {
                    self.listLoading = false;
                    let { msg, code, data } = res;
                    if (code === '999999') {
                        self.total = data.total;
                        self.dbList = data.data
                        this.totalCount=data.data.length
                    }else{
                        self.$message.error({
                            message: msg,
                            center: true,
                        })
                    }
                    })
            },
            indexMethod(index) {
                let curpage = this.page //单前页码，具体看组件取值
                let limitpage = 20//每页条数，具体是组件取值
                return (index + 1) + (curpage - 1) * limitpage
            },
             //跳转用
            handleResult: function (index, row) {
               let case_id=row.id
               this.$router.push({path:'/case_edit/cid='+case_id})
            },
             back(){
                 this.$router.go(-1)
                },
            backup: function (index, row) {
                this.detailFormVisible=true
            },
            // 改变项目状态
            handleChangeStatus: function(index, row) {
                let self = this;
                this.listLoading = true;
                let params = { case_id: row.id};
                let headers = {Authorization: 'Token '+JSON.parse(sessionStorage.getItem('token'))};
                    editStatus_case(headers, params).then(_data => {
                        let { msg, code, data } = _data;
                        self.listLoading = false;
                        if (code === '999999') {
                            self.$message({
                                message: msg,
                                center: true,
                                type: 'success'
                            });
                            row.delete_flag =!row.delete_flag
                        }
                        else {
                            self.$message.error({
                                message: msg,
                                center: true,
                            })
                        }
                    });
            },
            handleCurrentChange(val) {
                this.page = val;
                this.getDatebaseList()
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.editFormVisible = true;
                this.editForm = Object.assign({}, row);
            },
            //显示新增界面
            handleAdd: function () {
                this.addFormVisible = true;
            },

            handleBackup: function (index, row) {
                this.backupFormVisible = true;
                // 改变项目状态
                let self = this;
                this.databaseId=row.id
                let params = { db_id: row.id};//传数据库id到后台
                let headers = {Authorization: 'Token '+JSON.parse(sessionStorage.getItem('token'))};
                getTablebyDbID(headers, params).then((res) => {//根据数据库id获取数据库表信息
                    let { msg, code, data } = res;
                    if (code === '999999') {
                    this.databaseName=data.database
                    this.array = [{label: '全部', value: 'ALL'}]
                        for (var i=0;i<data.data.length;i++){
                            this.array.push({label:data.data[i],value:data.data[i]})
                        }
                    }else {
                        self.$message.error({
                            message: "失败",
                            center: true,
                        })
                    }
                })
            },

            selsChange: function (sels) {
                this.sels = sels;
            },

            handleSelect (val) {
                let selectVal = this.selectVal
                let oldSelectVal = this.oldSelectVal
                let arr = this.array
                let allValues = []
                // 保留所有值
                for (let item of arr) {
                    allValues.push(item.value)
                }
                if (val.includes('ALL')) {
                    if (!oldSelectVal.includes('ALL')) {
                        // 全选
                        selectVal = allValues
                    } else {
                    // 之前全选，点击非全选项，排除全选
                    const index = val.indexOf('ALL')
                    val.splice(index, 1)
                    selectVal = val
                    }
                } else {
                     if (oldSelectVal.includes('ALL')) {
                        // 取消全选
                        selectVal = []
                    } else if (allValues.length - 1 === val.length) {
                    // 全选没选，其他选项全部选上，选中全选
                    selectVal = allValues
                     }
                }
                this.selectVal = selectVal
                this.oldSelectVal = selectVal
            },

              //新增数据库配置
            backupDB: function () {
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        let self = this;
                        this.$confirm('确认备份选中的表结构和数据吗？', '提示', {}).then(() => {
                            self.addLoading = true;
                            //NProgress.start();
                            let params = JSON.stringify({
                                tablename: this.selectVal,
                                databasename: this.databaseName,
                                databaseId:this.databaseId
                            });

                            let header = {
                                "Content-Type": "application/json",
                                Authorization: 'Token '+JSON.parse(sessionStorage.getItem('token'))
                            };
                            addDatabase(header, params).then(_data => {
                                let {msg, code, data} = _data;
                                self.addLoading = false;
                                if (code === '999999') {
                                    self.$message({
                                        message: '添加成功',
                                        center: true,
                                        type: 'success'
                                    });
                                    self.$refs['addForm'].resetFields();
                                    self.addFormVisible = false;
                                    self.getDatebaseList()
                                } else if (code === '999997') {
                                    self.$message.error({
                                        message: msg,
                                        center: true,
                                    })
                                } else {
                                    self.$message.error({
                                        message: msg,
                                        center: true,
                                    });
                                    self.$refs['addForm'].resetFields();
                                    self.addFormVisible = false;
                                    self.getDatebaseList()
                                }
                            })
                        });
                    }
                });
            },
        },
        mounted() {
            this.getDatebaseList();
            this.initSelect()
        }
    }

</script>

<style>
.color-red{
   color: red;
   border: 1px solid #e8e8e8;
   padding: 0px 6px 0 9px;
   margin-right: 23px;
}
</style>
